<template>
    <el-popover :visible="visible" placement="bottom-end" :width="650" @show="handleShow">
        <div :class="$style['filter-wrapper']">筛选条件</div>
        <div :class="$style['filter-item']" v-for="(item, index) in json" :key="index">
            <div>{{ index + 1 }}</div>
            <el-select v-model="item.field" placeholder="请选择" @change="handleFieldChange(item)" clearable>
                <el-option v-for="row in modules" :key="row.field" :label="row.name" :value="row.field" />
            </el-select>
            <el-select v-model="item.condition" placeholder="请选择" clearable @change="handlConditionChange(item)">
                <el-option v-for="(row, key) in item.conditions" :key="key" :value="row.value" :label="row.name" />
            </el-select>
            <!--事件状态-->
            <el-select v-model="item.values" placeholder="请选择" v-if="item.field == 'status'">
                <el-option :value="1" label="未处理" />
                <el-option :value="2" label="已处理" />
            </el-select>
            <!--事件属性-->
            <el-select v-model="item.values" placeholder="请选择" v-if="item.field == 'type'">
                <el-option :value="1" label="设备发生" />
                <el-option :value="2" label="手工报警" />
            </el-select>
            <!--发生时间 || 处理时间-->
            <el-date-picker v-model="item.values" type="datetimerange" range-separator="~" format="YYYY-MM-DD HH:mm"
                value-format="YYYY-MM-DD HH:mm" start-placeholder="开始时间" end-placeholder="结束时间"
                v-if="item.type == 'date_time' && item.condition == 'between'" />

            <el-date-picker v-model="item.values" placeholder="选择时间" type="date" format="YYYY-MM-DD"
                value-format="YYYY-MM-DD" v-if="item.type == 'date_time' && item.condition == '='" />

            <!--事件名称-->
            <el-select v-model="item.values" placeholder="请选择" v-if="item.field == 'cid' && item.condition == '='">
                <el-option :label="row.event_name" :value="row.cid" v-for="(row, key) in events" :key="key" />
            </el-select>

            <el-select v-model="item.values" placeholder="请选择" multiple collapse-tags collapse-tags-tooltip
                :max-collapse-tags="3" v-if="item.field == 'cid' && item.condition == 'in'">
                <el-option :label="row.event_name" :value="row.cid" v-for="(row, key) in events" :key="key" />
            </el-select>

            <!--事件等级-->
            <el-select v-model="item.values" placeholder="请选择"
                v-if="item.field == 'event_level' && item.condition == '='">
                <el-option :label="row.name" :value="row.id" v-for="(row, key) in levels" :key="key" />
            </el-select>

            <el-select v-model="item.values" placeholder="请选择" multiple collapse-tags collapse-tags-tooltip
                :max-collapse-tags="3" v-if="item.field == 'event_level' && item.condition == 'in'">
                <el-option :label="row.name" :value="row.id" v-for="(row, key) in levels" :key="key" />
            </el-select>

            <!--事件分类-->
            <el-select v-model="item.values" placeholder="请选择"
                v-if="item.field == 'event_type' && item.condition == '='">
                <el-option :label="row.name" :value="row.id" v-for="(row, key) in types" :key="key" />
            </el-select>

            <el-select v-model="item.values" placeholder="请选择" multiple collapse-tags collapse-tags-tooltip
                :max-collapse-tags="3" v-if="item.field == 'event_type' && item.condition == 'in'">
                <el-option :label="row.name" :value="row.id" v-for="(row, key) in types" :key="key" />
            </el-select>

            <!--处理结果-->
            <el-select v-model="item.values" placeholder="请选择"
                v-if="item.field == 'handle_result' && item.condition == '='">
                <el-option :label="row.name" :value="row.id" v-for="(row, key) in results" :key="key" />
            </el-select>

            <el-select v-model="item.values" placeholder="请选择" multiple collapse-tags collapse-tags-tooltip
                :max-collapse-tags="3" v-if="item.field == 'handle_result' && item.condition == 'in'">
                <el-option :label="row.name" :value="row.id" v-for="(row, key) in results" :key="key" />
            </el-select>

            <!--处理用户-->
            <el-input v-model="item.values" placeholder="请输入" v-if="item.type == 'input'" />
            <el-select placeholder="请选择" v-if="!item.field">
            </el-select>
            <el-icon v-if="index > 0" @click="removeConditionItem(index)">
                <Delete />
            </el-icon>
        </div>
        <el-link :class="$style['add-link']" type="primary" :underline="false" :icon="Plus" @click="addConditionItem">
            添加
        </el-link>
        <div :class="$style['button-container']">
            <el-button size="small" @click="reset">重置</el-button>
            <div>
                <el-button size="small" @click="visible = false">取消</el-button>
                <el-button size="small" type="primary" @click="search">
                    筛选
                </el-button>
                <el-button size="small" type="primary" @click="openViewShow(1)">
                    新建视图
                </el-button>
                <el-button size="small" type="primary" v-if="view_id" @click="openViewShow(2)">
                    更新视图
                </el-button>
                <el-button size="small" type="danger" v-if="view_id" @click="removeItem">
                    删除视图
                </el-button>
            </div>
        </div>
        <template #reference>
            <el-button @click="visible = true">筛选</el-button>
        </template>
    </el-popover>
    <el-dialog v-model="viewShow" title="保存视图" width="500" :close-on-click-modal="false" :close-on-press-escape="false">
        <el-input v-model="addForm.name" placeholder="请输入视图名称" style="width:100%;"> </el-input>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="viewShow = false">取消</el-button>
                <el-button type="primary" @click="saveSubmit">保存</el-button>
            </div>
        </template>
    </el-dialog>
</template>
<script setup>
import { ref } from 'vue'
import { Delete, Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { fetchViewCreate, fetchViewRemove } from '@/api/view.services'
const emits = defineEmits(['search', 'updateView'])
const props = defineProps({
    events: {
        type: Array,
        default: () => []
    },
    levels: {
        type: Array,
        default: () => []
    },
    results: {
        type: Array,
        default: () => []
    },
    types: {
        type: Array,
        default: () => []
    },
    modules: {
        type: Array,
        default: () => []
    },
    views: {
        type: Array,
        default: () => []
    }
})
const json = ref([])
const visible = ref(false)
const view_id = ref(null)
const view_name = ref('')
const handleShow = () => {
    addForm.value = {}
    if (view_id.value) {
        json.value = props.views.find(item => item.id == view_id.value).json
    } else {
        json.value = [
            {
                field: '',
                condition: '',
                conditions: [],
                values: null
            }
        ]
    }
}
const addConditionItem = () => {
    json.value.push({
        field: '',
        condition: '',
        conditions: [],
        values: null
    })
}
const reset = () => {
    json.value = [
        {
            field: '',
            condition: '',
            conditions: [],
            values: null
        }
    ]
}
const handleFieldChange = (item) => {
    const row = props.modules.find(module => module.field == item.field)
    if (!row) return
    item.conditions = row.condition || []
    item.condition = ''
    item.type = row.type || ''
    handleDefaultValues(item)
}
const handleDefaultValues = (item) => {
    // 特殊处理日期类型
    if (item.condition === 'in' || item.condition === 'between') {
        item.values = []
        return
    }
    item.values = null
}
const handlConditionChange = (item) => {
    if (!item) return
    handleDefaultValues(item)
}
const removeConditionItem = (index) => {
    json.value.splice(index, 1)
}
const search = () => {
    emits('search', json.value)
}
const viewShow = ref(false)
const addForm = ref({})
const openViewShow = (type) => {
    const list = json.value.filter(item => (item.field && item.condition && item.values))
    if (list.length <= 0) {
        ElMessage.warning('请添加筛选条件')
        return
    }
    addForm.value = {
        json: list,
        uid: localStorage.getItem('uid'),
        type: 1
    }
    if (type == 2) {
        addForm.value.id = view_id.value
        addForm.value.name = view_name.value
    }
    viewShow.value = true
}
const saveSubmit = async () => {
    if (!addForm.value?.name) {
        ElMessage.warning('请输入视图名称')
        return
    }
    const result = await fetchViewCreate(addForm.value)
    if (result.code == 1) {
        ElMessage.success('保存成功')
        viewShow.value = false
        visible.value = false
        view_id.value = null
        view_name.value = ''
        addForm.value = {}
        emits('updateView')
    }
}
const removeItem = async () => {
    if (!view_id.value) return
    try {
        await ElMessageBox.confirm('确定删除该视图吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })
        await fetchViewRemove({ id: view_id.value })
        ElMessage.success('删除成功')
        visible.value = false
        view_id.value = null
        view_name.value = ''
        emits('updateView')
    } catch (error) {
        console.error(error)
    }
}
defineExpose({
    view_id,
    view_name
})
</script>
<style lang="scss" module>
.filter-wrapper {
    width: 100%;
    height: 35px;
    line-height: 35px;
    border-bottom: 1px solid #ccc;
}

.add-link {
    height: 30px;
}

.filter-item {
    display: flex;
    flex-direction: row;
    justify-content: flex-start;
    height: 40px;
    align-items: center;

    &> :nth-child(1) {
        width: 24px;
        height: 24px;
        line-height: 24px;
        border-radius: 50%;
        border: 1px solid #406ce0;
        color: #406ce0;
        text-align: center;
    }

    &> :nth-child(2) {
        width: 100px;
        margin-left: 10px;
    }

    &> :nth-child(3) {
        width: 80px;
        margin-left: 10px;
    }

    &> :nth-child(4) {
        width: 365px;
        margin-left: 10px;
        box-sizing: border-box;
    }

    &> :nth-child(5) {
        margin-left: 10px;
    }
}

.button-container {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    height: 50px;
    border-top: 1px solid #ccc;
}
</style>
